require 'net/http'
require 'rexml/document'

class Tools::NumberLocationsController < ApplicationController  
  before_filter :authorize, :except => :index_in_show
  
  def index
    @setting = UserToolSetting.find(params[:setting_id])
    @location = NumberLocation.new(params[:number]) if params[:number].present?
  end
  
  def copy
    @setting  = UserToolSetting::NumberLocation.find(params[:id])
    @new = UserToolSetting::NumberLocation.new(
      @setting.attributes.keys.each_with_object({}) do |key,hash|
        hash[key] = @setting.attributes[key] unless [:id,
          :created_at,
          :updated_at,
          :emails_count,
          :sms_count         
        ].include?(key)
      end
    )
    @new.save
    @settings = UserToolSetting.all_by_current_user_by_column @new.column
  end
  
  def destroy
    @setting = UserToolSetting::NumberLocation.find(params[:id])
    render :text => '', :status => @setting.destroy ? 200 : 500
  end
    
  def index_in_show
    @tool = Tool.find_by_code('number_location')
    @settings = UserToolSetting::NumberLocation.find_all_by_user_id_and_tool_id(current_user_id, @tool.id)
  end
  
  def new_in_show
    @tool = Tool.find_by_code('number_location')
    @province = Province.first
    @setting = UserToolSetting::NumberLocation.new(:column => @tool.default_column)
  end
  
  def create_in_show    
    @tool = Tool.find_by_code('number_location')
    @setting = UserToolSetting::NumberLocation.new(params[:user_tool_setting_number_location])
    @setting.attributes = {
      :user_id => current_user_id,
      :tool_id => @tool.id
    }
    if @setting.save
      redirect_to :action => :index_in_show, :format => :js
    else
      @province = Province.first
      render :new_in_show
    end
  end
  
  def edit_in_show    
    @setting = UserToolSetting::NumberLocation.find(params[:id])
    @tool = Tool.find_by_code('number_location')
  end
  
  def update_in_show
    @setting = UserToolSetting::NumberLocation.find(params[:id])
    @tool = @setting.tool
    if @setting.update_attributes(params[:user_tool_setting_number_location])
      redirect_to :action => :index_in_show, :format => :js
    else
      @province = Province.first
      render :edit_in_show
    end
  end
  
  def destroy_in_show
    @setting = UserToolSetting::NumberLocation.find(params[:id])
    render :text => '', :status => @setting.destroy ? 200 : 500
  end
end

